package com.uls.framework.utils;


import com.alibaba.fastjson.JSONObject;
import com.google.api.client.util.IOUtils;

import com.uls.framework.config.MinioProp;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@Component
public class MinioUtils {
 
    @Autowired
    private MinioClient client;

    @Autowired
    private MinioProp minioProp;

 
    /**
     * 创建bucket
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    public void createBucket(String bucketName) {
        if (!client.bucketExists(bucketName)) {
            client.makeBucket(bucketName);
        }
    }

 
    /**
     * 上传文件
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
        public JSONObject uploadFile(MultipartFile file, String bucketName) throws Exception {
        JSONObject res = new JSONObject();
        res.put("code", 0);
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            res.put("msg", "上传文件不能为空");
            return res;
        }
        try {
	       	// 判断存储桶是否存在
	        createBucket(bucketName);
	        // 文件名
	        String originalFilename = file.getOriginalFilename();
	        // 新的文件名 = 存储桶名称_时间戳.后缀名
	        String fileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
	        // 开始上传
	        client.putObject(bucketName, fileName, file.getInputStream(), file.getContentType());
	        res.put("code", 1);
	        res.put("msg", minioProp.getEndpoint() + "/" + bucketName + "/" + fileName);
	        return res;
		}  catch (Exception e) {
            log.error("上传文件失败：{}", e.getMessage());
        }
        res.put("msg", "上传失败");
        return res;
    }


    /**
     * 删除桶中文件
     * @param name
     * @return
     */
    @SneakyThrows(Exception.class)
    public String delete(String name) {
            client.removeObject(minioProp.getBucket(),name);
            return null;
    }


    /**
     * 判断 bucket是否存在
     *
     * @param bucketName 桶名
     * @return: boolean
     */
    @SneakyThrows(Exception.class)
    public  boolean bucketExists(String bucketName) {
        return client.bucketExists(bucketName);
    }


    /**
     *
     * 获取全部bucket
     * @return: java.util.List<io.minio.messages.Bucket>
     */
    @SneakyThrows(Exception.class)
    public List<Bucket> getAllBuckets() {
        return client.listBuckets();
    }



    /**
     *
     * 获取minio文件的下载地址
     * @param bucketName 桶名
     * @param fileName  文件名
     */
    @SneakyThrows(Exception.class)
    public  String getFileUrl(String bucketName, String fileName) {
        return client.presignedGetObject(bucketName, fileName);
    }


    /**
     * 下载文件 （流输出）
     * @param bucketName  桶名
     * @param fileName 文件名
     */
    @SneakyThrows(Exception.class)
    public  void download(String bucketName, String fileName, HttpServletResponse response) {
        // 获取对象的元数据
        final ObjectStat stat = client.statObject(bucketName, fileName);
        response.setContentType(stat.contentType());
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream is = client.getObject(bucketName, fileName);
        IOUtils.copy(is, response.getOutputStream());
        is.close();
    }





}
